package com.exam.dao;

import com.exam.domain.entity.User;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;


public class UserDao {

    // 通过用户名获取用户
    public User getUserByUserName(String userName) {
        String sql = "SELECT * FROM users WHERE username = ?";
        // 执行查询操作，返回结果集
        // 执行查询操作，返回 ResultSet
        try {
            Connection connection = DBUtil.getConnection();
            ResultSet rs = DBUtil.query(connection, sql, userName);
            if (rs.next()) {
                // 结果集中有数据，映射到 User 对象
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUserName(rs.getString("username"));
                user.setUserType(rs.getString("user_type"));
                user.setPassword(rs.getString("password"));
                // 返回查询到的用户
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询用户失败", e);
        }
        // 如果没有找到用户，返回 null
        return null;

    }


}
